package com.yonyou.iuap.jxzy.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.iuap.base.web.BaseController;
import com.yonyou.iuap.generic.adapter.impl.InvocationInfoProxy;
import com.yonyou.iuap.jxzy.entity.WastePaperHeadVO;
import com.yonyou.iuap.jxzy.service.WastePaperBodyService;
import com.yonyou.iuap.jxzy.service.WastePaperHeadService;
import com.yonyou.iuap.mvc.type.SearchParams;
import com.yonyou.metadata.mybatis.util.publish.model.data.UFDateTime;

/**
 * iuap 进口废纸查询审核，取消审核，短重，导出功能
 * @author wanggp
 * @date 2019年6月5日
 */
@Controller
@RequestMapping(value="/jx_importedPaper")
public class IUapImportPaperController extends BaseController{

	private Logger logger= LoggerFactory.getLogger(ImportWastePaperController.class);

	private WastePaperHeadService wasteheadservice; 

	private WastePaperBodyService wastebodyservice;


	@Autowired
	public void setWastePaperHeadService(WastePaperHeadService wasteheadservice) {
		this.wasteheadservice = wasteheadservice;
	}

	@Autowired
	public void setWastePaperBodyService(WastePaperBodyService wastebodyservice) {
		this.wastebodyservice = wastebodyservice;
	}
	
	/**
	 * 短重范围权限管理
	 * @param request
	 * @param response
	 * @param json
	 * @return
	 */
	@RequestMapping(value="/rangeweightAuthorities",method=RequestMethod.POST)
	@ResponseBody
	public Object rangeweightAuthorities(HttpServletRequest request,HttpServletResponse response){
		boolean result=false;
//		String userid=InvocationInfoProxy.getInstance().getUserid();获取不到
		String userCode=null;
		Cookie[]  cookies=request.getCookies();
		if (cookies!=null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("_A_P_userLoginName")) {
                	userCode = cookie.getValue();
                }
            }
		}
		logger.error("测试cookies获取用户编码："+userCode);
		JSONObject jsono=new JSONObject();
		try {
			result=this.wasteheadservice.queryrangeweightAuthorities(userCode);//更新磅单短重范围
		} catch (Exception e) {
			jsono.put("success", "error");
			jsono.put("message", "短重范围权限控制失败：原因是"+e.getMessage());
			return jsono;
		}
		return this.buildSuccess(result);
	}
	
	@RequestMapping(value="/rangeweight",method=RequestMethod.POST)
	@ResponseBody
	public Object rangeweight(HttpServletRequest request,HttpServletResponse response,@RequestBody String json){
		JSONObject object = JSONObject.parseObject(json);
		String weightData=object.get("weightData")!=null?object.get("weightData").toString():null;//短重
		String poundNo=object.get("poundNo")!=null?object.get("poundNo").toString():null;//磅单号
		JSONObject jsono=new JSONObject();
		int result=0;
		try {
			result=this.wasteheadservice.rangeweight(poundNo,weightData);//更新磅单短重范围
		} catch (Exception e) {
			jsono.put("success", "error");
			jsono.put("message", "短重范围更新失败：原因是"+e.getMessage());
			return jsono;
		}
		return this.buildSuccess("短重范围更新："+result+"条");
	}
	
	/**
	 * iuap进口废纸审核
	 * @author wanggp
	 * @throws IOException 
	 */
	@RequestMapping(value="/verify", method=RequestMethod.POST)
	@ResponseBody
	public Object verify(HttpServletRequest request,HttpServletResponse response, @RequestBody String json) throws IOException{
		JSONObject object = JSONObject.parseObject(json);
		com.alibaba.fastjson.JSONArray array = object.getJSONArray("param");
		List<WastePaperHeadVO> wasteHeadvos = array.toJavaList(WastePaperHeadVO.class);
		String userCode=null;//审核人编码
		Cookie[]  cookies=request.getCookies();
		if (cookies!=null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("_A_P_userLoginName")) {
					userCode = cookie.getValue();
				}
			}
		}
		for(WastePaperHeadVO headvo:wasteHeadvos){
			headvo.setAuditor(userCode);
			headvo.setAuditortime(new UFDateTime().toString());
		}
		JSONObject jsono=new JSONObject();
		int result=0;
		try {
			result=this.wasteheadservice.verify(wasteHeadvos);//审核
		} catch (Exception e) {
			jsono.put("success", "error");
			jsono.put("message", "审核失败：原因是"+e.getMessage());
			return jsono;
		}
		return this.buildSuccess("审核："+result+"条");
	}
	
	/**
	 * iuap进口废纸取消审核
	 * @author wanggp
	 * @throws IOException 
	 */
	@RequestMapping(value="/cancelverify", method=RequestMethod.POST)
	@ResponseBody
	public Object cancelverify(HttpServletRequest request,HttpServletResponse response,@RequestBody String json) throws IOException{
		JSONObject object = JSONObject.parseObject(json);
        com.alibaba.fastjson.JSONArray array = object.getJSONArray("param");
        List<String> poundlist =new ArrayList<String>();
        for(int i = 0; i < array.size(); i++){
            JSONObject o = array.getJSONObject(i);
            poundlist.add(o.get("poundNo")!=null?o.get("poundNo").toString():null);
        }
		int result=0;
		JSONObject jsono=new JSONObject();
		try {
			result=this.wasteheadservice.cancelverify(poundlist);//取消审核
		} catch (Exception e) {
			jsono.put("success", "error");
			jsono.put("message", "取消审核失败：原因是"+e.getMessage());
			return jsono;
		}
		return	this.buildSuccess("取消审核："+result+"条");
	}
	
	
	/**
	 * 查询iuap进口废纸
	 * @author wanggp
	 */
	@RequestMapping(value="/list")
	@ResponseBody
	public Object list(PageRequest pageRequest, SearchParams searchParams){
		Page<WastePaperHeadVO> page=null;
		Map<String, Object> searchMap = searchParams.getSearchMap();
    	if(searchMap.get("pk_material")!=null){
    		String string = searchMap.get("pk_material").toString();
    		searchMap.put("pk_material", string.replace(",", "','"));
    	}
    	if(searchMap.get("heapNo")!=null){
    		String string = searchMap.get("heapNo").toString();
    		searchMap.put("heapNo", string.replace(",", "','"));
    	}
		page=this.wasteheadservice.selectAllByPage(pageRequest, searchParams);//分页查询
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("data", page);
		return this.buildMapSuccess(map);
	}
	
	/**
	 * iuap进口废纸更新
	 * @param headvo
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/save")
	@ResponseBody
	public Object save(@RequestBody WastePaperHeadVO headvo,HttpServletRequest request,HttpServletResponse response){
		int result=0;
		String userCode=null;//修改人编码
		Cookie[]  cookies=request.getCookies();
		if (cookies!=null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("_A_P_userLoginName")) {
					userCode = cookie.getValue();
				}
			}
		}
		try {
			headvo.setModifyuser(userCode);
			result=this.wasteheadservice.updateWasterPaper(headvo);
		} catch (Exception e) {
			return this.buildJsonFail("更新进口废纸失败"+e.getMessage());
		}
		return this.buildSuccess("进口废纸更新成功："+result+"条");
		
	}
}
